package cn.sdjzu.exercise;

import java.io.IOException;

import cn.sdjzu.exercise.db.DBHelper;
import android.content.ContentValues;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class TestPositionActivity extends TransmissionActivity implements
		OnClickListener {

	private EditText mPosition;
	private Button mTestBackBtn;
	private Button mAdjustSeatBtn;
	private Button mTestStartBtn;
	private Button mTestOKBtn;
	private SendDataThread sendDataThread;
	private boolean isRunning;
	ExerciseApp app;
	private int SendFlag;
	private int ReciveOverTime;
	private TextView countdown5;
	static final int COUNT_DOWN54321 = 0;
	static final int COUNT_DOWN54321_FINISH = 1;
	boolean countdownFinishFlg = false;
	boolean isPauseFlg = false;
	boolean Reset=false;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ExerciseApp.getInstance().addActivity(this);
		setContentView(R.layout.test_position);
		app = (ExerciseApp) TestPositionActivity.this.getApplication();
		DBNoDataToast = Toast.makeText(this, "数据库出错", Toast.LENGTH_LONG);
		mPosition = (EditText) findViewById(R.id.test_position_edit_position);
		mPosition.setHeight(TureEditH);
		mTestBackBtn = (Button) findViewById(R.id.test_position_back);
		mAdjustSeatBtn = (Button) findViewById(R.id.test_position_adjust_seat);
		mTestStartBtn = (Button) findViewById(R.id.test_position_start);
		mTestOKBtn = (Button) findViewById(R.id.test_position_ok);
		countdown5 = (TextView) findViewById(R.id.pos_countdown5);
		mTestBackBtn.setOnClickListener(this);
		mAdjustSeatBtn.setOnClickListener(this);
		mTestStartBtn.setOnClickListener(this);
		mTestOKBtn.setOnClickListener(this);
		isRunning = false;
	}

	@Override
	public void onResume() {
		super.onResume();
		LayoutParams pos;
		pos = mPosition.getLayoutParams();
		pos.height = EditH;
		mPosition.setLayoutParams(pos);
	}

	@Override
	protected void onPause() {
		shutdownConn();
		super.onPause();
	}

	public void shutdownConn() {
		if (sendDataThread != null) {
			sendDataThread.interrupt();
		}
		super.shutdownConn();
	}

	Handler mhandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case COUNT_DOWN54321:
				countdown5.setText(String.valueOf(msg.obj));
				break;
			case COUNT_DOWN54321_FINISH:
				countdown5.setVisibility(View.GONE);
				break;
			}
		}
	};

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.test_position_ok:
			Reset=true;
			String positionStr = mPosition.getText().toString();
			try {
				position = Integer.parseInt(positionStr);
			} catch (Exception e) {
				Toast.makeText(this, "invalid data", Toast.LENGTH_LONG).show();
				return;
			}
			DBHelper dbHelper = new DBHelper(this);
			ContentValues values = new ContentValues();
			values.put(DBHelper.TBL_USER_CARDNO, app.currentCardNo);
			values.put(DBHelper.TBL_USER_EXT_POSITION, position);
			if (dbHelper.isExistCardNoInDB(DBHelper.TBL_USER_EXT,
					app.currentCardNo)) {
				dbHelper.updateUserExtData(values);
			} else {
				dbHelper.insertData2DB(DBHelper.TBL_USER_EXT, values);
			}
			try {
				mOutputStream.write(CHANGE_WORK_STATE0);
				changeTXT(CHANGE_WORK_STATE0);
			} catch (IOException e) {
				e.printStackTrace();
			}
			isRunning = false;
			ResetThread reset=new ResetThread();
			reset.start();
			break;
		case R.id.test_position_adjust_seat:
			isRunning = false;
			AdjustSeatActivity.fromWhich = "testposition";
			Intent intentSeat = new Intent(this, AdjustSeatActivity.class);
			startActivity(intentSeat);
			break;

		case R.id.test_position_start:
			isRunning = !isRunning;
			if (isRunning) {
				// 计数完成标志判断
				if (countdownFinishFlg) {// 完成则方发送模式与力量数据
					try {
						ReciveOverTime = 0;
						while (SendFlag != 0 && ReciveOverTime < 200) {
							ReciveOverTime++;
							Thread.sleep(1); // dong add
						}
						mOutputStream.write(CRCChecker.getFinalSendBytes(
								SET_SETTING_FORCE_PREFIX, 100));
						changeTXT(CRCChecker.getFinalSendBytes(
								SET_SETTING_FORCE_PREFIX, 100));
						SendFlag = 1;
						Thread.sleep(1000); // dong add
						ReciveOverTime = 0;
						while (SendFlag != 0 && ReciveOverTime < 200) {
							ReciveOverTime++;
							Thread.sleep(1); // dong add
						}
						mOutputStream.write(CHANGE_WORK_STATE5);
						changeTXT(CHANGE_WORK_STATE5);
						SendFlag = 2;
						Thread.sleep(1000);
						ReciveOverTime = 0;
						while (SendFlag != 0 && ReciveOverTime < 200) {
							ReciveOverTime++;
							Thread.sleep(1); // dong add
						}
						mOutputStream.write(GET_MAXBALL_LOCATION);
						changeTXT(GET_MAXBALL_LOCATION);
						SendFlag = 3;
						isRunning = true;
						// 发送
						sendDataThread = new SendDataThread();
						sendDataThread.start();
					} catch (IOException e) {
						e.printStackTrace();
					} catch (Exception e) {
						e.printStackTrace();
					}
				} else {// 计数未完成（发送模式后计数54321）
					countdown5.setText("预备");
					try {
						mOutputStream.write(CHANGE_WORK_STATE5);
						//changeTXT(CHANGE_WORK_STATE5);
						Thread.sleep(1000);
						mOutputStream.write(CRCChecker.getFinalSendBytes(
								SET_SETTING_FORCE_PREFIX, 100));
						changeTXT(CRCChecker.getFinalSendBytes(
								SET_SETTING_FORCE_PREFIX, 100));
					} catch (IOException e) {
						e.printStackTrace();
					} catch (Exception e) {
						e.printStackTrace();
					}
					// 计数线程开启
					CountDownThread countDownThread = new CountDownThread();
					countDownThread.start();
				}
				mTestStartBtn.setText(getResources().getString(
						R.string.exercise_pause));
			} else {
				// 暂停
				mTestStartBtn.setText(getResources().getString(R.string.start));
			}
			break;
		case R.id.test_position_back:
			isRunning = false;
			Intent intent3 = new Intent(this, ControlPanelActivity.class);
			startActivity(intent3);
			this.finish();
			break;
		default:
			break;
		}
	}

	class SendDataThread extends Thread {
		public void run() {

			while (isRunning && !isInterrupted()) {
				try {
					ReciveOverTime = 0;
					while (SendFlag == 3 && ReciveOverTime < 200) {
						ReciveOverTime++;
						Thread.sleep(1); // dong add
					}
					Thread.sleep(200);
					mOutputStream.write(GET_MAXBALL_LOCATION);
					changeTXT(GET_MAXBALL_LOCATION);
					SendFlag = 3;
				} catch (IOException e) {
					e.printStackTrace();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}

	class ResetThread extends Thread {
		public void run() {
//			countdown5.setVisibility(View.VISIBLE);
//			countdown5.setTextSize(40);
//			countdown5.setText("请等待机器复位完毕。。。");
			try {
				Thread.sleep(9000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			Intent intent1 = new Intent(TestPositionActivity.this, ControlPanelActivity.class);
			startActivity(intent1);
			TestPositionActivity.this.finish();
			
		}
	}

	class CountDownThread extends Thread {
		int count = 5;
		public void run() {
			do {
				try {
					Thread.sleep(500);
					if (count > 0) {
						countdown5.setVisibility(View.VISIBLE);
						mhandler.obtainMessage(COUNT_DOWN54321, count)
								.sendToTarget();
						Thread.sleep(500);
						count--;
					} else {
						Thread.sleep(500);
						mhandler.obtainMessage(COUNT_DOWN54321_FINISH)
								.sendToTarget();
						countdownFinishFlg = true;
						sendDataThread = new SendDataThread();
						isPauseFlg = false;
						sendDataThread.start();
					}
				} catch (Exception e) {
					Log.d(TAG, "mCountdown5", e);
				}
			} while (!countdownFinishFlg);
		}
	}

	@Override
	protected void onDataReceived(final byte[] buffer, int size, final int count) {
		final byte[] crctest = new byte[count];
		for (int i = 0; i < count; i++) {
			crctest[i] = buffer[i];
		}
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				changeTXT1(crctest);
				if (CRCChecker.checkBuf(crctest)) {
					changeTXT1(crctest);
					if (SendFlag == 3&&Reset==false) {
						int x = (int) crctest[4];
						int y = (int) crctest[3];
						if (x < 0) {
							x += 256;
						}
						if (y < 0) {
							y += 256;
						}
						y = y * 256 + x;
						if(y<1000){ 
						mPosition.setText(y + "");}
					}
					SendFlag = 0;
				}
			}
		});
	}

	public void onBackPressed() {
		isRunning = false;
		Intent intent3 = new Intent(this, ControlPanelActivity.class);
		startActivity(intent3);
		this.finish();
	}
}
